package com.syni.mdd.yhd.common.all.controller.pay.aliPay;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayFundTransOrderQueryModel;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.syni.mdd.yhd.common.all.config.pay.alipay.AlipayConfig;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.controller.pay.wxPay.WxPayController;
import com.syni.mdd.yhd.common.all.dto.requestDto.pay.PayReDto;
import com.syni.mdd.yhd.common.all.entity.BmsDxOrder;
import com.syni.mdd.yhd.common.all.entity.record.ReTransferLog;
import com.syni.mdd.yhd.common.all.service.BmsDxOrderService;
import com.syni.mdd.yhd.common.all.service.pay.aiPay.AliPayService;
import com.syni.mdd.sjb.common.component.utils.common.utils.ArithUtil;
import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.ParamsMap;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.sjb.common.component.utils.redis.utils.RedisTemplateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.syni.mdd.yhd.common.all.utils.AliPayUtil.getOrderNo;
import static com.syni.mdd.yhd.common.all.utils.AliPayUtil.getRequestNo;

;


@RestController
@RequestMapping("/aliPay")
public class AliPayController {

    @Autowired
    private AliPayService aliPayService;

    @Autowired
    BmsDxOrderService bmsDxOrderService;

    @Autowired
    WxPayController wxPayController;

    @Autowired
    @Qualifier("oldAliPayConfig")
    AlipayConfig oldAliPayConfig;

    @Autowired
    @Qualifier("aliPayConfig")
    AlipayConfig alipayConfig;

    @Autowired
    @Qualifier("aliMiniAppConfig")
    AlipayConfig aliMiniAppConfig;

    private final Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 发起支付
     * @param merchantId 个体商户号
     * @param subject 支付标题
     * @param body 支付内容
     * @param totalAmt 支付金额（元）
     * @return
     */
    /*@CheckParams(params = {"orderId","orderNo"})
    @PostMapping("/prepay")
    @ResponseBody
    public Map<String,Object> prepay(@RequestBody Map<String,Object> paramsMap){
        Map<String,Object> resultMap = new HashMap<>();
        Integer orderId = Integer.parseInt(paramsMap.get("orderId").toString());
        String orderNo = paramsMap.get("orderNo").toString();
        //检验订单号和订单id是否一致
        Optional<BmsDxOrder> bmsDxOrderOptional = bmsDxOrderService.getBaseDao().findById(orderId);
        if(!bmsDxOrderOptional.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_EXIST, ResultMsg.CODE_ORDER_NO_EXIST);
        }
        BmsDxOrder bmsDxOrder = bmsDxOrderOptional.get();
        if(!bmsDxOrder.getOrderNo().equals(orderNo)){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_ID_NOMATCH_NO, ResultMsg.CODE_ORDER_ID_NOMATCH_NO);
        }
        Map<String,Object> checkMap = bmsDxOrderService.checkOrderCanPay(bmsDxOrder);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        String totalAmt = bmsDxOrder.getActualConsum().toString();
        try {
            // 这个东西必备
            AlipayClient alipayClient = new DefaultAlipayClient(
                    serverUrl,
                    appid,
                    private_key,
                    "json",
                    "UTF-8",
                    alipay_public_key,
                    "RSA2");
            // 发起App支付请求
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            // 订单描述
            model.setBody(AlipayServiceImpl.PAY_DEFAULT_DESC);
            // 订单标题
            model.setSubject(aliPayService.getOrderSubject(bmsDxOrder));
            // 商户订单号 就是商户后台生成的订单号
            model.setOutTradeNo(orderNo);
            // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天 (屁股后面的字母一定要带，不然报错)
            model.setTimeoutExpress("30m");
            // 订单总金额 ，默认单位为元，精确到小数点后两位，取值范围[0.01,100000000]
            model.setTotalAmount(totalAmt);
            // 销售产品码 不必填
            model.setProductCode("QUICK_MSECURITY_PAY");
            request.setBizModel(model);
            request.setNotifyUrl(callBackUrl);
            // 通过api的方法请求阿里接口获得反馈
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            if (response.isSuccess()) {
                System.out.println("支付调用成功");
            } else {
                System.out.println("支付调用失败");
            }
            //TODO 保存订单
            String result = response.getBody();
            resultMap.put("payCredent",result);
            System.out.println(result);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return ResultMapHelper.result(ResultCode.CODE_PAY_ID_GET_FIAR,"支付凭证获取失败");
        }
        return ResultMapHelper.success(resultMap,ResultMsg.MSG_GET_SUCCESS);
    }*/




    /**
     * 分账商户绑定
     * @param data 绑定商户信息列表
     */
    @PostMapping("relationBind")
    @ResponseBody
    public Map<String,Object> bind (@RequestBody PayReDto payReDto){
        String errorMsg = ResultMsg.ADMIN_ERROR;
        JSONObject receiver = new JSONObject();
        receiver.put("type","userId");
        receiver.put("account",payReDto.getBusinessPayId());
        receiver.put("name",payReDto.getPayName());
        receiver.put("memo",String.format("分账给%s",payReDto.getPayName()));
        JSONArray receiverList = new JSONArray();
        receiverList.add(receiver);
        try{
            AlipayClient alipayClient = aliPayService.getAlipayClient();
            AlipayTradeRoyaltyRelationBindRequest request = new AlipayTradeRoyaltyRelationBindRequest();
            String requestNo = getOrderNo();
            JSONObject params = new JSONObject();
            params.put("out_request_no",requestNo);
            params.put("receiver_list",receiver);
            System.out.println(params);
            request.setBizContent(params.toString());
//        request.setBizContent("{" +
//                "      \"receiver_list\":[{" +
//                "        \"type\":\"userId\"," +
//                "\"account\":\"2088521539689611\"," +
//                "\"name\":\"珠海西江生态农业发展有限公司\"," +
//                "\"memo\":\"分账给珠海西江生态农业发展有限公司\"" +
//                "        }]," +
//                "\"out_request_no\":\"2019071200000001\"" +
//                "  }");
//        request.setBizContent(params.toString());
            AlipayTradeRoyaltyRelationBindResponse response = alipayClient.execute(request);
            String body = response.getBody();
            System.out.println("body:"+body);
            if(response.isSuccess()){
                //同时进行解绑
                Map<String,Object> paramMap = new HashMap<>();
                paramMap.put("account",payReDto.getBusinessPayId());
                paramMap.put("accountName",payReDto.getPayName());
                //return ResultMapHelper.success(ResultMsg.HAND_SUCCESS);
                Map<String,Object> retMap = this.unbind(paramMap);
                if(retMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(retMap.get("status").toString())) {
                    return ResultMapHelper.success(ResultMsg.HAND_SUCCESS);
                }
            }
            errorMsg = response.getSubMsg();
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return ResultMapHelper.failure(errorMsg);
    }

    /**
     * 分账商户解除绑定
     * @return
     */
    @PostMapping("relationUnbind")
    @ResponseBody
    public Map<String,Object> unbind(@RequestBody Map<String,Object> paramsMap){
        String errorMsg = ResultMsg.ADMIN_ERROR;
        String account = paramsMap.get("account").toString();
        String accountName = paramsMap.get("accountName").toString();
        Map<String,Object> params = new HashMap<>();
        AlipayClient alipayClient = aliPayService.getAlipayClient();
        AlipayTradeRoyaltyRelationUnbindRequest request = new AlipayTradeRoyaltyRelationUnbindRequest();
        AlipayTradeRoyaltyRelationUnbindResponse response = null;
       /* request.setBizContent("{" +
                "      \"receiver_list\":[{" +
                "        \"type\":\"userId\"," +
                "\"account\":\""+account+"\"," +
                "\"name\":\""+accountName+"\"," +
                "\"memo\":\"解除绑定"+accountName+"\"" +
                "        }]," +
                "\"out_request_no\":\"2019071200000002\"" +
                "  }");*/
        JSONObject receiver = new JSONObject();
        receiver.put("type","userId");
        receiver.put("account",account);
        receiver.put("name",accountName);
        receiver.put("memo",String.format("解除绑定%s",accountName));
        JSONArray receiverList = new JSONArray();
        receiverList.add(receiver);
        System.out.println(UUID.randomUUID().toString().length());
        params.put("out_request_no",getRequestNo());
        params.put("receiver_list",receiverList);
        request.setBizContent(JSON.toJSONString(params));
        try {
            response = alipayClient.execute(request);
            String body = response.getBody();
            System.out.println("body:"+body);
            if(response.isSuccess()){
                return ResultMapHelper.success(ResultMsg.HAND_SUCCESS);
            }
            errorMsg = response.getSubMsg();
        } catch (AlipayApiException e) {
            log.error(e.getMessage(),e);
        }
        return ResultMapHelper.failure(errorMsg);
    }

    /**
     * 查询分账关系
     * @param requestNo
     */
    @PostMapping("query")
    @ResponseBody
    public Map<String,Object> query(@RequestBody Map<String,Object> paramsMap){
        String requestNo = getRequestNo();
        AlipayClient alipayClient = aliPayService.getAlipayClient();
        AlipayTradeRoyaltyRelationBatchqueryRequest request = new AlipayTradeRoyaltyRelationBatchqueryRequest();
        Map<String,Object> conditionMap = new HashMap<>();
        Integer pageNum = Integer.parseInt(paramsMap.get("pageNum").toString());
        Integer pageSize = Integer.parseInt(paramsMap.get("pageSize").toString());
        conditionMap.put("page_num",pageNum);
        conditionMap.put("page_size",pageSize);
        conditionMap.put("out_request_no",requestNo);
        /*request.setBizContent("{" +
                "\"page_num\":1," +
                "\"page_size\":20," +
                "\"out_request_no\":\""+requestNo+"\"" +
                "  }");*/
        request.setBizContent(JSON.toJSONString(conditionMap));
        AlipayTradeRoyaltyRelationBatchqueryResponse response = null;
        try {
            response = alipayClient.execute(request);
            if(response.isSuccess()){
                System.out.println(".....调用成功......");
                String responseBody = response.getBody();
                Map<String,Object> resultMap = JSON.parseObject(responseBody);
                return ResultMapHelper.success(resultMap,ResultMsg.MSG_GET_SUCCESS);
            }
        } catch (AlipayApiException e) {
            log.error(e.getMessage(),e);
        }
        return ResultMapHelper.failure(ResultMsg.ADMIN_ERROR);
    }

    /**
     * 分账接口
     * @param tradeNo 支付宝单号
     * @param transOut 分账支出账号
     * @param transIn 分账收入账号
     * @param amount 分账金额
     */
    //@PostMapping("settle")
    //@ResponseBody
    //@CheckParams(checkAuth = true)
    //public void settle(String tradeNo,String transOut,String transIn,Double amount){
    public void settle(){
        AlipayClient alipayClient = aliPayService.getAlipayClient();
        AlipayTradeOrderSettleRequest request = new AlipayTradeOrderSettleRequest();
        String orderNo = getOrderNo();

        Map<String,Object> params = new HashMap<>();
        params.put("out_request_no","201910221035396870P3EI94g");
        params.put("trade_no","2019102222001447960525967131");

        /*Map<String,Object> b1 = new HashMap<>();
        b1.put("royalty_type","transfer");
        b1.put("trans_out","2088031456998454");
        b1.put("trans_out_type","userId");
        b1.put("trans_in_type","userId");
        b1.put("trans_in","2088202891261412");
        b1.put("amount","0.1");
        b1.put("desc","分账给烺....");*/

        Map<String,Object> b2 = new HashMap<>();
        b2.put("royalty_type","transfer");
        b2.put("trans_out","2088031456998454");
        b2.put("trans_out_type","userId");
        b2.put("trans_in_type","userId");
        b2.put("trans_in","2088632127947964");
        b2.put("amount","0.9");
        b2.put("desc","分账给融通黎明....");

        JSONArray jsonArray = new JSONArray();
        //jsonArray.add(b1);
        jsonArray.add(b2);

        params.put("royalty_parameters",jsonArray);

        request.setBizContent(JSON.toJSONString(params));

        /*request.setBizContent("{" +
                "\"out_request_no\":\""+orderNo+"\"," +
                "\"trade_no\":\""+tradeNo+"\"," +
                "      \"royalty_parameters\":[{" +
                "        \"royalty_type\":\"transfer\"," +
                "\"trans_out\":\""+transOut+"\"," +
                "\"trans_out_type\":\"userId\"," +
                "\"trans_in_type\":\"userId\"," +
                "\"trans_in\":\""+transIn+"\"," +
                "\"amount\":"+amount+"," +
                "\"desc\":\"分账给"+transIn+"\"" +
                "        }]," +
                "\"operator_id\":\"A0001\"" +
                "  }");*/
        AlipayTradeOrderSettleResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            log.error(e.getMessage(),e);
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }


    public Map<String,Object> settleForService(String payNo, String businessPayId, String total){
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("status",ResultCode.CODE_ERROR);
        AlipayClient alipayClient = aliPayService.getAlipayClient();
        AlipayTradeOrderSettleRequest request = new AlipayTradeOrderSettleRequest();
        String requestNo = getRequestNo();

        Map<String,Object> params = new HashMap<>();
        params.put("out_request_no",requestNo);
        params.put("trade_no",payNo);

        Map<String,Object> settleBusiness = new HashMap<>();
        settleBusiness.put("royalty_type","transfer");
        settleBusiness.put("trans_out",alipayConfig.getCompanyPayNo());
        settleBusiness.put("trans_out_type","userId");
        settleBusiness.put("trans_in_type","userId");
        settleBusiness.put("trans_in",businessPayId);
        settleBusiness.put("amount",total);
        settleBusiness.put("desc","分账给：" + businessPayId);
        System.out.println("分账用户：" + JSON.toJSONString(settleBusiness));
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(settleBusiness);
        params.put("royalty_parameters",jsonArray);
        //设置请求
        request.setBizContent(JSON.toJSONString(params));
        AlipayTradeOrderSettleResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            log.error(e.getMessage(),e);
            resultMap.put("settleError",e.toString());
        }
        resultMap.put("settleData",JSON.toJSONString(response));
        System.out.println("分账信息：" + JSON.toJSONString(response));
        if(response.isSuccess()){
            System.out.println(payNo + ":" + businessPayId + ":" + total);
            System.out.println(".....分账成功....");
            resultMap.put("status", ResultCode.CODE_NORMAL);
        }
        return resultMap;
    }

    /**
     * 退款接口
     * @param tradeNo 支付宝单号
     * @param refundAmount 退款金额
     * @param refundReason 退款理由
     */
    //@PostMapping("refund")
    //@ResponseBody
    public void refund(String tradeNo,Double refundAmount,String refundReason,String qas){
        if(!qas.equals("09190014a.")){
            return;
        }
        AlipayClient alipayClient = aliPayService.getAlipayClient();
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        String orderNo = getOrderNo();

        Map<String,Object> b1 = new HashMap<>();
        b1.put("out_trade_no",tradeNo);
        b1.put("refund_amount",refundAmount);
        b1.put("refund_reason",refundReason);
        b1.put("out_request_no",getRequestNo());
        request.setBizContent(JSON.toJSONString(b1));
        /*request.setBizContent("{" +
                "\"out_trade_no\":\""+orderNo+"\"," +
                "\"trade_no\":\""+tradeNo+"\"," +
                "\"refund_amount\":"+refundAmount+"," +
                "\"refund_reason\":\""+refundReason+"\"," +
                "\"out_request_no\":\"HZ01RF001\"," +
                "\"operator_id\":\"OP001\"," +
                "\"store_id\":\"NJ_S_001\"," +
                "\"terminal_id\":\"NJ_T_001\"," +
//                "      \"goods_detail\":[{" +
//                "        \"goods_id\":\"apple-01\"," +
//                "\"alipay_goods_id\":\"20010001\"," +
//                "\"goods_name\":\"ipad\"," +
//                "\"quantity\":1," +
//                "\"price\":2000," +
//                "\"goods_category\":\"34543238\"," +
//                "\"categories_tree\":\"124868003|126232002|126252004\"," +
//                "\"body\":\"特价手机\"," +
//                "\"show_url\":\"http://www.alipay.com/xxx.jpg\"" +
//                "        }]," +
//                "      \"refund_royalty_parameters\":[{" +
//                "        \"royalty_type\":\"transfer\"," +
//                "\"trans_out\":\"2088101126765726\"," +
//                "\"trans_out_type\":\"userId\"," +
//                "\"trans_in_type\":\"userId\"," +
//                "\"trans_in\":\"2088101126708402\"," +
//                "\"amount\":0.1," +
//                "\"amount_percentage\":100," +
//                "\"desc\":\"分账给2088101126708402\"" +
//                "        }]," +
//                "\"org_pid\":\"2088101117952222\"" +
                "  }")*/;
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            log.error(e.getMessage(),e);
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }


    /**
     * @Description 用户端退款接口
     * @Author: cfx
     * @Date: 2019/8/2
     */
    //@PostMapping("refundOrder")
    //@CheckParams(checkAuth = true,params = {"orderId","groupBuyUseIds"})
    public synchronized Map<String,Object> refundOrder(@RequestBody ParamsMap paramsMap) throws Exception {
        Integer orderId = paramsMap.getInteger("orderId");
        BmsDxOrder bmsDxOrder = bmsDxOrderService.getBaseDao().findByIdAndIsDelete(orderId, Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxOrder == null){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_REFUND_TOO_LOGN,"退款超时,请重试");
        }
        Map<String,Object> userDataMap = new HashMap<>();
        try {
            if(bmsDxOrder.getCreateWay() == null){
                bmsDxOrder.setCreateWay(Constants.ANDROID_CLIENT);
            }
            if(bmsDxOrder.getCreateWay() == Constants.WECHAT_MINAPP){
                userDataMap = wxPayController.refund(paramsMap);
            }else if(bmsDxOrder.getCreateWay() == Constants.ANDROID_CLIENT){
                AlipayClient alipayClient = aliPayService.getAlipayClient();
                AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
                userDataMap = aliPayService.refund(alipayClient,request,paramsMap);
            }
        }catch (Exception e){
            log.info(e.toString());
            userDataMap = ResultMapHelper.result(ResultCode.CODE_ORDER_REFUND_TOO_LOGN,"退款超时,请重试");
        }finally {
            return userDataMap;
        }
    }

    /**
     * 支付结果回调
     */
    @PostMapping("/AppAliPayNotify")
    public void appAliPayNotify() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try{
            aliPayService.appAliPayNotify(request,alipayConfig.getPublicKey());
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    /**
     * 支付结果回调
     */
    @PostMapping("/AliMinAppPayNotify")
    public synchronized void AliMinAppPayNotify() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try{
            aliPayService.appAliPayNotify(request,aliMiniAppConfig.getPublicKey());
        }catch (Exception e){
            log.error("aliPay callback error : ",e);
        }
    }

    /**
     * 支付结果回调
     */
    @PostMapping("/appPayServicePayNotify")
    public synchronized void microServicePayNotify() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
        try{
            aliPayService.appPayServicePayNotify(request,response);
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }


    /**
     * 转账
     */
    //@GetMapping("/transfer")
    public Map<String,Object> transfer() {
        AlipayClient alipayClient = aliPayService.getAlipayClient();
        AlipayFundTransToaccountTransferRequest  request = new AlipayFundTransToaccountTransferRequest();
        Map<String,Object> b1 = new HashMap<>();
        b1.put("out_biz_no",getRequestNo());
        b1.put("payee_type","ALIPAY_USERID");
        b1.put("payee_account","2088122109309865");
        b1.put("amount","11.40");

        request.setBizContent(JSON.toJSONString(b1));
        AlipayFundTransToaccountTransferResponse  response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            log.error(e.getMessage(),e);
        }
        if(response.isSuccess()){
            log.info("转账成功............");
        }
        //aliPayService.transfer();
        return ResultMapHelper.success(null,"ok");
    }

    public Map<String,Object> transferFullCoupon(BmsDxOrder bmsDxOrder,String businessPayId, String total,ReTransferLog transferLog) {
        businessPayId = businessPayId.replaceAll(" ","");
        transferLog.setNewTime(new Date());
        transferLog.setBusinessPayId(businessPayId);
        transferLog.setOrderId(bmsDxOrder.getId());
        transferLog.setTotal(Double.parseDouble(total));
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("status",ResultCode.CODE_ERROR);
        if(!RedisTemplateUtils.noHasKey(Constants.REDIS_ORDER_TRANS_LOCKING + bmsDxOrder.getId(),5)){
            return resultMap;
        }
        AlipayClient alipayClient = aliPayService.getAlipayClient();
//        AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
//        AlipayFundTransUniTransferModel alipayFundTransUniTransferModel = new AlipayFundTransUniTransferModel();
//        alipayFundTransUniTransferModel.setOutBizNo(getRequestNo());
//        alipayFundTransUniTransferModel.setTransAmount(total);
//        alipayFundTransUniTransferModel.setProductCode("TRANS_ACCOUNT_NO_PWD");
//        alipayFundTransUniTransferModel.setOrderTitle("觅东东平台转账");
//        Participant payeeInfo = new Participant();
//        payeeInfo.setIdentity(businessPayId);
//        payeeInfo.setIdentityType("ALIPAY_USERID");
//        alipayFundTransUniTransferModel.setPayeeInfo(payeeInfo);
//        alipayFundTransUniTransferModel.setRemark("觅东东平台团购转账-" + businessPayId);
        AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
        String requestNo = getRequestNo();
        Map<String,Object> b1 = new HashMap<>();
        b1.put("out_biz_no",requestNo);
        b1.put("payee_type","ALIPAY_USERID");
        b1.put("payee_account",businessPayId);
        b1.put("amount",total);
        b1.put("remark","觅东东平台团购转账-" + businessPayId);
        //b1.put("remark",getOrderSubject(bmsDxOrder));

        request.setBizContent(JSON.toJSONString(b1));
        AlipayFundTransToaccountTransferResponse  response = null;
        try {
            //将当前订单锁住
            RedisTemplateUtils.getRedisTemplate().opsForValue().set(Constants.REDIS_ORDER_TRANS_LOCKING + bmsDxOrder.getId(),bmsDxOrder.getId());
            response = alipayClient.execute(request);
            resultMap.put("transferData",JSON.toJSONString(response));
            transferLog.setTransferData(resultMap.get("transferData").toString());
            transferLog.setStatus(Constants.COMMON_FLAG_FALSE_INT);
            if(response.isSuccess()) {
                //确认查询
                AlipayFundTransOrderQueryRequest alipayFundTransOrderQueryRequest = new AlipayFundTransOrderQueryRequest();
                AlipayFundTransOrderQueryModel alipayFundTransOrderQueryModel = new AlipayFundTransOrderQueryModel();
                alipayFundTransOrderQueryModel.setOutBizNo(requestNo);
                alipayFundTransOrderQueryRequest.setBizModel(alipayFundTransOrderQueryModel);
                AlipayFundTransOrderQueryResponse alipayFundTransOrderQueryResponse = alipayClient.execute(alipayFundTransOrderQueryRequest);
                log.info("transQuery:" + JSON.toJSONString(alipayFundTransOrderQueryResponse));
                if(alipayFundTransOrderQueryResponse.isSuccess() && "SUCCESS".equals(alipayFundTransOrderQueryResponse.getStatus())){
                    Double settlementAmount = Double.parseDouble(total);
                    bmsDxOrder.setSettlementAmount(bmsDxOrder.getSettlementAmount() == null ? settlementAmount : ArithUtil.add(bmsDxOrder.getSettlementAmount(),settlementAmount));
                    bmsDxOrderService.getBaseDao().save(bmsDxOrder);
                    resultMap.put("status", ResultCode.CODE_NORMAL);
                    transferLog.setStatus(Constants.COMMON_FLAG_TRUE_INT);
                }
            }
        }catch (AlipayApiException e) {
            log.error("transferError: ",e);
            resultMap.put("transferError",e.toString());
        }finally {
            RedisTemplateUtils.delete(Constants.REDIS_ORDER_TRANS_LOCKING + bmsDxOrder.getId());
        }
        return resultMap;
    }


    /**
     * 支付结果回调
     */
    @PostMapping("/queryOrder")
    public Map<String,Object> queryOrder(@RequestBody ParamsMap paramsMap) {

        Integer old = paramsMap.getInteger("old");
            AlipayClient alipayClient = aliPayService.getAlipayClient();
        if(old == 1){
            Integer nowTime = DateTimeUtils.converDateToInterger(DateTimeUtils.converStringToDate("2019-02-13 20:30:00",DateTimeUtils.DATE_PATTERN_TIMESTAMP));
            alipayClient = aliPayService.getAlipayClient(nowTime);
        }
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            Map<String,Object> queryMap = new HashMap<>();
            //queryMap.put("out_trade_no",bmsDxOrder.getOrderNo());
            queryMap.put("out_trade_no",paramsMap.get("orderNo"));
            //定制可选项
            queryMap.put("query_options",new String[]{"TRADE_SETTE_INFO"});
            System.out.println(JSON.toJSONString(queryMap));
            request.setBizContent(JSON.toJSONString(queryMap));
            AlipayTradeQueryResponse response = null;
            try {
                response = alipayClient.execute(request);
            } catch (AlipayApiException e) {
                log.error(e.getMessage(),e);
            }
            if(response.isSuccess()){
                Map<String,Object> resultMap = new HashMap<>();
                resultMap.put("body",response.getBody());
                resultMap.put("tradeSettleInfo",response.getTradeSettleInfo());
                return ResultMapHelper.success(resultMap,"ok");
            }
        return ResultMapHelper.failure(ResultMsg.CODE_ORDER_NO_EXIST);
    }
}
